package com.mpsc.sharding.util;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ShardingJdbcDemo {
    public static void main(String[] args) throws SQLException {

        //一、配置数据库
        Map<String, DataSource> dataSourceMap = new HashMap(2);
        //配置第一个数据库
        HikariDataSource dataSource0 = new HikariDataSource();
        dataSource0.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource0.setJdbcUrl("jdbc:mysql://localhost:3306/sharding_1?characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dataSource0.setUsername("root");
        dataSource0.setPassword("123456");
        dataSourceMap.put("m1", dataSource0);
        //配置第二个数据库
        HikariDataSource dataSource1 = new HikariDataSource();
        dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource1.setJdbcUrl("jdbc:mysql://localhost:3306/sharding_2?characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dataSource1.setUsername("root");
        dataSource1.setPassword("123456");
        dataSourceMap.put("m2", dataSource1);

        //二、配置分库分表策略
        //配置分片规则
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
//        //真实表分布
//        TableRuleConfiguration courseTableRuleConfig =
//                new TableRuleConfiguration("user_entity",
//                        "m$->{1..2}.user_entity_{1..2}");
//        //主键策略
//        courseTableRuleConfig.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id", getProps()));
//        //真实库分布
//        courseTableRuleConfig.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("id", "m$->{cid%2+1}"));
//        courseTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("id", "m$->{cid%2+1}"));
//        shardingRuleConfig.getTableRuleConfigs().add(courseTableRuleConfig);

        //--------------------------------------------------------------------------------------------------------------------------------------------
        //绑定表配置
        //shardingRuleConfig.getBindingTableGroups().add("t_order,t_order_item");
        //配置默认分库策略（可选）
        //shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration());
        //配置默认分表策略（可选）
//        shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("cid", new PreciseShardingAlgorithm() {
//            @Override
//            public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
//                for (String each: collection){
//                    if(each.endsWith(preciseShardingValue.getValue() % 2+"")){
//                        return  each;
//                    }
//                }
//                throw new UnsupportedOperationException();
//            }
//        }));

        //三、配置属性值
        Properties properties = new Properties();
        //打印日志输出
        properties.setProperty("sql.show","true");
        //创建shardingSphere的数据源shardingDataSource
        DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap,shardingRuleConfig,properties);

        //--------测试部分----------//
        ShardingJdbcDemo test = new ShardingJdbcDemo();
        //建表

        //插入数据

        //调试的起点，查询数据

        test.queryCourse(dataSource);
    }

    private static Properties getProps() {

        Properties properties = new Properties();
        properties.setProperty("id", "123");
        return properties;
    }



    public void queryCourse(DataSource dataSource) throws SQLException {
        Connection connection = null;

        try {
            connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            String sql = "";
            ResultSet resultSet =statement.executeQuery(sql);
            while (resultSet.next()){
                System.out.println("result:"+ resultSet.getLong("cid"));
            }

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            if(null != connection){
                connection.close();
            }
        }
    }

}
